from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.utils.translation import gettext_lazy as _

"""建模说明

由于每门课程的章节要建立目录，这要求一次性查询一门课程的所有章节标题，
但是不需要加载所有章节内容，因此把章节内容和标题分开存。

"""


class Chapter(models.Model):
    name = models.CharField(max_length=64, null=False, blank=False)
    course = models.ForeignKey(
        'course.Course', on_delete=models.CASCADE, related_name="chapters")

    #  ID
    next_id = models.PositiveBigIntegerField(null=True, blank=True)

    # 修改相应的 document 时需要手动更新
    updated_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'chapters'

    def __str__(self) -> str:
        return f'<Chapter No.{self.id} {self.name} for {self.course}>'


class ChapterText(models.Model):

    content = models.TextField(null=False, blank=False, default="待完成")
    chapter = models.OneToOneField(
        Chapter, on_delete=models.CASCADE, related_name='chapter_text')
    updated_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'chapter_texts'

    def __str__(self) -> str:
        return f'<ChapterText No.{self.id} for {self.chapter}>'


@receiver(post_save, sender=Chapter)
def create_default_chapter_text(sender, instance, created, **kwargs):
    if created:
        ChapterText.objects.create(
            chapter=instance, content="快来添加内容吧")
